package ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import main.ErrorException;
import main.ErrorHandler;

import config.ConfigType;
import define.Common;
import define.Config;

public class MenuGroup implements ActionListener, PopupListener
{
	private JMenu m_menu;
	private ArrayList<JMenuItem> m_menuItems;
	private ArrayList<ConfigType> m_types;
	private int m_selectIndex;
	
	public MenuGroup(String name, int group)
	{
		m_menu = new JMenu(name);
		m_menuItems = new ArrayList<JMenuItem>();
		m_types = new ArrayList<ConfigType>();
		for(ConfigType ct: ConfigType.values())
		{
			if(ct.getGroup() == group)
			{
				m_types.add(ct);
				JMenuItem mi = new JMenuItem(ct.getMenuShowText());
				m_menuItems.add(mi);
				m_menu.add(mi);
				mi.addActionListener(this);
			}
		}
	}
	
	public void addToMenuBar(JMenuBar bar)
	{
		bar.add(m_menu);
	}
	
	public void changeText(ConfigType ct)
	{
		for(int i = 0, size = m_types.size(); i < size; ++i)
		{
			if(m_types.get(i) == ct)
			{
				m_menuItems.get(i).setText(ct.getMenuShowText());
			}
		}
	}

	public void actionPerformed(ActionEvent e) 
	{
		if(Common.m_isRunning)
		{
			return;
		}
		Object s = e.getSource();
		m_selectIndex = 0;
		for(int size = m_menuItems.size(); m_selectIndex < size; ++m_selectIndex)
		{
			if(s == m_menuItems.get(m_selectIndex))
			{
				break;
			}
		}
		new Popup(Window.m_instance.getMainWindow(), m_types.get(m_selectIndex).getPopupShowText(), m_types.get(m_selectIndex).getStringValue(), this);
	}

	public void onClose(String text)
	{
		if(text != null)
		{
			try
			{
				m_types.get(m_selectIndex).setValue(text, Config.NO_POSITION);
			} 
			catch(ErrorException e) 
			{
				new ErrorHandler(e);
			}
		}
	}
}
